package demo.bean.handler;


import demo.bean.BeanFactory;
import demo.bean.InjectHandler;
import demo.bean.annotations.Inject;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//set方法注入
public class MethodInjectHandler implements InjectHandler {
    public void execute(Object target, Class<?> targetClass, BeanFactory factory) throws IllegalAccessException, InstantiationException {
        try {
            //Object o = targetClass.newInstance();
            BeanInfo beanInfo = Introspector.getBeanInfo(targetClass, Object.class);
            PropertyDescriptor[] psd = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor p:psd){
                //使用getWriteMethod() 为类的属性赋值。
                Method writeMethod = p.getWriteMethod();
                if (writeMethod.isAnnotationPresent(Inject.class)){
                    String value = writeMethod.getAnnotation(Inject.class).value();
                    Object bean = factory.getBean(value);
                    writeMethod.invoke(target,bean);
                }
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
